package com.maimao.auth.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.maimao.api.auth.CodeApi;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.IPUtil;
import com.maimao.core.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.maimao.core.constant.RedisKeys.LOGIN_PREFIX;

/**
 * @author MaoLin Wang
 * @date 2020/12/14 1:28 下午
 */
@Slf4j
@RestController("/")
public class CodeController extends BaseController implements CodeApi {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${auth.code.duration}")
    private Integer duration;

    /**
     * 发送手机验证码 TODO 整合阿里大于
     */
    @Override
    @PostMapping("/mobile-code")
    public Result<String> mobileCode(@RequestBody Map<String, String> data,
                                     @RequestParam(name = "defaultMobile", required = false, defaultValue = "0") Integer defaultMobile) {
        String mobile = data.get("mobile");
        if (StringUtils.isEmpty(mobile)) {
            return Result.notValid("请填写手机号");
        }
        if (!RegexUtils.checkPhone(mobile)) {
            return Result.notValid("手机号格式非法");
        }
        String text = defaultKaptcha.createText();
        if (duration == null) {
            duration = 60;
        }
        stringRedisTemplate.opsForValue().set(RedisKeys.LOGIN_MOBILE_PREFIX + mobile, text, duration, TimeUnit.SECONDS);
        log.info("生成手机验证码:{} => {}", mobile, text);
        return Result.ok();
    }

    /**
     * 生成图形验证码
     */
    @Override
    @GetMapping("/image-code")
    public void imageCode() throws IOException {
        // 获取验证码字符串
        String code = defaultKaptcha.createText();
        log.info("生成图形验证码: {}" + code);
//        getSession().setAttribute(LOGIN_PREFIX,code);
        // 字符串把它放到redis中，有效期1分钟 todo
        String ipAddress = IPUtil.getIpStr(getRequest());
        stringRedisTemplate.opsForValue().set(LOGIN_PREFIX + ipAddress, code, 3, TimeUnit.MINUTES);
        // 获取验证码图片
        BufferedImage image = defaultKaptcha.createImage(code);
        // 将验证码图片写出去
        ServletOutputStream out = getResponse().getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
}
